package com.shuyun.controller;

import com.shuyun.controller.request.PullDataRequest;
import com.shuyun.controller.request.PushDataRequest;
import com.shuyun.controller.response.PullDataResponse;
import com.shuyun.controller.response.PushDataResponse;
import com.shuyun.service.RocketMQService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: shuai.chen@shuyun.com
 * @date: 2022/10/9 3:35 PM
 */
@RestController
@RequestMapping("callback")
@Slf4j
public class HelloController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RocketMQService rocketMQService;

    /**
     * 推送数据
     *
     * @param request
     *            推送数据
     * @return 回执
     */
    @PostMapping("push")
    public PushDataResponse pushData(@RequestBody PushDataRequest request) throws MQClientException {
        String destination = "open_token_to_partner";
        String tag = request.getTag();
        if (StringUtils.isNotBlank(tag)) {
            destination = destination + ":" + tag;
        }
        SendResult sendResult = rocketMQTemplate.syncSend(destination, request.getData());
        return new PushDataResponse(sendResult.getMsgId());
    }

    /**
     * 拉取数据
     *
     * @param request
     *            拉取数据
     * @return 回执
     */
    @PostMapping("pull")
    public PullDataResponse pullData(@RequestBody PullDataRequest request) {
        String tag = request.getTag();
        RocketMQTemplate rocketMQTemplate1 = rocketMQService.getRocketMQTemplateByTag(tag);
        List<MessageExt> data = null;
        if (StringUtils.isBlank(tag) || StringUtils.equals("*", tag)) {
            data = rocketMQTemplate1.receive(MessageExt.class);
        } else {
            data = rocketMQTemplate.receive(MessageExt.class);
        }
        List<String> callback = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(data)) {
            for (MessageExt messageExt : data) {
                String bodyStr = new String(messageExt.getBody(), StandardCharsets.UTF_8);
                callback.add(bodyStr);
            }
        }
        return new PullDataResponse(callback);
    }

}
